<?php


require_once 'Objects/User.php';

/**
 * Makes User objects
 * @author DePhille
 *
 */
class UserFactory {
	private static $loggedInUser;	// The currently logged in user.
	
	/**
	 * Gets the current logged in user.
	 * 	Might be a guest user.
	 * 
	 * @return	The user object corresponding to this HTTP session.
	 */
	public function getCurrent() {
		// Fetch logged in user from cache if possible:
		if (self::$loggedInUser) {
			return self::$loggedInUser;
		}
		
		// Fetch token string:
		$token = HTTPHandler::getHeader("PCToken");
		if (!$token) {
			self::$loggedInUser = $this->makeGuest();
			return self::$loggedInUser;
		}
		
		// Fetch the user attached to the token:
		$tokenObj = TokenTable::getByString($token);
		if (!$tokenObj) {
			Logger::log("UserFactory", "Given token does not exist.");
			self::$loggedInUser = $this->makeGuest();
			return self::$loggedInUser;			
		}
		
		// Fetch user:
		$user = $tokenObj->getUser();
		if (!$user) {
			Logger::log("UserFactory", "Given token has no valid user attached to it.");
			self::$loggedInUser = $this->makeGuest();
			return self::$loggedInUser;
		}
		
		// Store user in cache and return:
		self::$loggedInUser = $user;
		return self::$loggedInUser;		
	}
	
	/**
	 * Creates a Guest user.
	 * 
	 * @return A guest User
	 */
	public function makeGuest() {
		// Make object:
		$user = new User();
		
		// Assign values:
		$user->setID(0);
		$user->setPassword("guest");
		$user->setUsername("Guest");
		$user->setAuthorized(FALSE);
		
		// Return object:
		return $user;
	}
	
	
	/**
	 * Builds a User object from a given database row.
	 * 
	 * @param databaseRow An asociative array representing the row in the database.
	 * @return A newly made User object.
	 */
	public function fromRow($databaseRow) {
		// Check if a valid row was given:
		if (!is_array($databaseRow)) {
			return NULL;
		}
		
		// Make user object:
		$user = new User();
		
		// Fill in ID:
		if (isset($databaseRow["id"])) {
			$user->setID($databaseRow["id"]);
		}
		
		// Fill in username:
		if (isset($databaseRow["username"])) {
			$user->setUsername($databaseRow["username"]);
		}
		
		// Fill in password:
		if (isset($databaseRow["password"])) {
			$user->setPassword($databaseRow["password"]);
		}
		
		// Mark authorization:
		if (isset($databaseRow["id"]) && isset($databaseRow["username"]) && isset($databaseRow["password"])) {
			$user->setAuthorized(true);
		} else {
			$user->setAuthorized(false);
		}
		
		// Return USer object:
		return $user;
	}

}
?>
